package com.cenntro.oss.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.time.DateUtils;

import com.alicloud.openservices.tablestore.SyncClient;
import com.alicloud.openservices.tablestore.model.ColumnValue;
import com.alicloud.openservices.tablestore.model.Direction;
import com.alicloud.openservices.tablestore.model.GetRangeRequest;
import com.alicloud.openservices.tablestore.model.GetRangeResponse;
import com.alicloud.openservices.tablestore.model.PrimaryKeyBuilder;
import com.alicloud.openservices.tablestore.model.PrimaryKeyValue;
import com.alicloud.openservices.tablestore.model.RangeRowQueryCriteria;
import com.alicloud.openservices.tablestore.model.Row;
import com.alicloud.openservices.tablestore.model.filter.SingleColumnValueFilter;
import com.cenntro.oss.model.vo.TrackLogVO;

public class AliTableStoreService {
	private static String endPoint = "https://cenntrodb.cn-hangzhou.ots.aliyuncs.com";// 外网地址：
	// private static String endPoint =
	// "https://cenntrodb.cn-hangzhou.ots.aliyuncs.com";//内网地址：
	private static String accessId = "LTAIDq699IsaizxQ";
	private static String accessKey = "Dp9jbC2Dx3MJ5FigANGLAHYKYk8SbW";
	private static String instanceName = "cenntrodb";
//	private static String gpslog = "gpslog";
//	private static String vehiclelog = "vehiclelog";
	private static String tracklog = "tracklog";
	  
//	private static String dbName = "";//选择使用的db
	private static SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式

	private SyncClient client;

	private static AliTableStoreService _instance = null;

	public static AliTableStoreService getInstance() {
		if (_instance == null)
			_instance = new AliTableStoreService();
		return _instance;
	}

	public AliTableStoreService() {
		client = new SyncClient(endPoint, accessId, accessKey, instanceName);
	}

	/*
	 * 获取车辆日志数据列表 status: 0x01 启动状态2、0x02熄火 3、0x03其他状态 4、0xfe 异常5、0xff无效
	 */
	public List<TrackLogVO> getlistTrackLog(String vincode, Date beginTime, Date endTime) {
		long from = beginTime.getTime();
		long to = endTime.getTime();
		int days = (int) ((to - from) / (1000 * 60 * 60 * 24));
		if (days > 7) {
			Calendar c = Calendar.getInstance();
			c.setTime(beginTime);
			c.add(Calendar.DAY_OF_MONTH, 7);// 今天+1天
			endTime = c.getTime();
		}
		ArrayList<TrackLogVO> getList = new ArrayList<TrackLogVO>();

		SingleColumnValueFilter single1 = new SingleColumnValueFilter("speed", SingleColumnValueFilter.CompareOperator.GREATER_THAN, ColumnValue.fromDouble(0));

		RangeRowQueryCriteria rangeRowQueryCriteria = new RangeRowQueryCriteria(tracklog);
		rangeRowQueryCriteria.setLimit(10000);
		rangeRowQueryCriteria.setDirection(Direction.FORWARD);
		rangeRowQueryCriteria.setMaxVersions(1);
		rangeRowQueryCriteria.setFilter(single1);
		// 设置起始主键
		PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
		primaryKeyBuilder.addPrimaryKeyColumn("vincode", PrimaryKeyValue.fromString(vincode));
		primaryKeyBuilder.addPrimaryKeyColumn("time", PrimaryKeyValue.fromString(df.format(beginTime)));
		primaryKeyBuilder.addPrimaryKeyColumn("status", PrimaryKeyValue.fromLong(2));
		rangeRowQueryCriteria.setInclusiveStartPrimaryKey(primaryKeyBuilder.build());
		// 设置结束主键
		primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
		primaryKeyBuilder.addPrimaryKeyColumn("vincode", PrimaryKeyValue.fromString(vincode));
		primaryKeyBuilder.addPrimaryKeyColumn("time", PrimaryKeyValue.fromString(df.format(endTime)));
		primaryKeyBuilder.addPrimaryKeyColumn("status", PrimaryKeyValue.fromLong(5));
		rangeRowQueryCriteria.setExclusiveEndPrimaryKey(primaryKeyBuilder.build());

		while (true) {
			GetRangeResponse getRangeResponse = client.getRange(new GetRangeRequest(rangeRowQueryCriteria));
			for (Row row : getRangeResponse.getRows()) {
				// System.out.println(row);
				TrackLogVO nowM = new TrackLogVO();
				try {
					nowM.setImei(vincode);
					nowM.setAddress(row.getColumn("address").get(0).getValue().asString());
					nowM.setBaidulat(row.getColumn("baidulat").get(0).getValue().asString());
					nowM.setBaidulng(row.getColumn("baidulng").get(0).getValue().asString());
					nowM.setLat(row.getColumn("lat").get(0).getValue().asString());
					nowM.setLng(row.getColumn("lng").get(0).getValue().asString());
					nowM.setDoor(row.getColumn("door").get(0).getValue().toString());
					nowM.setSpeed(row.getColumn("speed").get(0).getValue().toString());
					nowM.setTodir(row.getColumn("todir").get(0).getValue().toString());
					double soc = row.getColumn("soc").get(0).getValue().asDouble();
					nowM.setBattery((int)soc);
					nowM.setFaraway(row.getColumn("mileage").get(0).getValue().asDouble());
					nowM.setUptime(row.getPrimaryKey().getPrimaryKeyColumn("time").getValue().toString());
					
					nowM.setCreatetime(DateUtils.parseDateStrictly(nowM.getUptime(), new String[]{"yyyyMMddHHmmss"}));
					if ("".equals(nowM.getBaidulat()) || nowM.getBaidulat().indexOf("0") == 0 || "".equals(nowM.getBaidulng()) || nowM.getBaidulng().indexOf("0") == 0)
						continue;
					if (nowM.getBaidulng().indexOf("110") == 0 && nowM.getBaidulng().indexOf("10") == 0)
						continue;
					getList.add(nowM);
				} catch (Exception e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
			// 若nextStartPrimaryKey不为null, 则继续读取.
			if (getRangeResponse.getNextStartPrimaryKey() != null) {
				rangeRowQueryCriteria.setInclusiveStartPrimaryKey(getRangeResponse.getNextStartPrimaryKey());
			} else {
				break;
			}
		}
		return getList;
	}
	
	 
	
	/*
     * 获取车辆日志数据列表 status: 0x01 启动状态2、0x02熄火 3、0x03其他状态 4、0xfe 异常5、0xff无效
     */
    public List<TrackLogVO> getlistTrackLog2(Integer devId, String vincode, Date beginTime, Date endTime, String dbname) {
        long from = beginTime.getTime();
        long to = endTime.getTime();
        int days = (int) ((to - from) / (1000 * 60 * 60 * 24));
        if (days > 7) {
            Calendar c = Calendar.getInstance();
            c.setTime(beginTime);
            c.add(Calendar.DAY_OF_MONTH, 7);// 今天+1天
            endTime = c.getTime();
        }
        ArrayList<TrackLogVO> getList = new ArrayList<TrackLogVO>();

        SingleColumnValueFilter single1 = new SingleColumnValueFilter("speed", SingleColumnValueFilter.CompareOperator.GREATER_THAN, ColumnValue.fromDouble(0));

        RangeRowQueryCriteria rangeRowQueryCriteria = new RangeRowQueryCriteria(dbname);
        rangeRowQueryCriteria.setLimit(10000);
        rangeRowQueryCriteria.setDirection(Direction.FORWARD);
        rangeRowQueryCriteria.setMaxVersions(1);
        rangeRowQueryCriteria.setFilter(single1);
        // 设置起始主键
        PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
        primaryKeyBuilder.addPrimaryKeyColumn("devId", PrimaryKeyValue.fromLong(devId));
        primaryKeyBuilder.addPrimaryKeyColumn("time", PrimaryKeyValue.fromString(df.format(beginTime)));
        primaryKeyBuilder.addPrimaryKeyColumn("status", PrimaryKeyValue.fromLong(2));
        rangeRowQueryCriteria.setInclusiveStartPrimaryKey(primaryKeyBuilder.build());
        // 设置结束主键
        primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
        primaryKeyBuilder.addPrimaryKeyColumn("devId", PrimaryKeyValue.fromLong(devId));
        primaryKeyBuilder.addPrimaryKeyColumn("time", PrimaryKeyValue.fromString(df.format(endTime)));
        primaryKeyBuilder.addPrimaryKeyColumn("status", PrimaryKeyValue.fromLong(5));
        rangeRowQueryCriteria.setExclusiveEndPrimaryKey(primaryKeyBuilder.build());

        while (true) {
            GetRangeResponse getRangeResponse = client.getRange(new GetRangeRequest(rangeRowQueryCriteria));
            for (Row row : getRangeResponse.getRows()) {
                // System.out.println(row);
                TrackLogVO nowM = new TrackLogVO();
                try {
                    nowM.setImei(vincode);
                    nowM.setAddress(row.getColumn("address").get(0).getValue().asString());
                    nowM.setBaidulat(row.getColumn("baidulat").get(0).getValue().asString());
                    nowM.setBaidulng(row.getColumn("baidulng").get(0).getValue().asString());
                    nowM.setLat(row.getColumn("lat").get(0).getValue().asString());
                    nowM.setLng(row.getColumn("lng").get(0).getValue().asString());
                    nowM.setDoor(row.getColumn("door").get(0).getValue().toString());
                    nowM.setSpeed(row.getColumn("speed").get(0).getValue().toString());
                    nowM.setTodir(row.getColumn("todir").get(0).getValue().toString());
                    double soc = row.getColumn("soc").get(0).getValue().asDouble();
                    nowM.setBattery((int)soc);
                    nowM.setFaraway(row.getColumn("mileage").get(0).getValue().asDouble());
                    nowM.setUptime(row.getPrimaryKey().getPrimaryKeyColumn("time").getValue().toString());
                    
                    nowM.setCreatetime(DateUtils.parseDateStrictly(nowM.getUptime(), new String[]{"yyyyMMddHHmmss"}));
                    if ("".equals(nowM.getBaidulat()) || nowM.getBaidulat().indexOf("0") == 0 || "".equals(nowM.getBaidulng()) || nowM.getBaidulng().indexOf("0") == 0)
                        continue;
                    if (nowM.getBaidulng().indexOf("110") == 0 && nowM.getBaidulng().indexOf("10") == 0)
                        continue;
                    getList.add(nowM);
                } catch (Exception e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
            }
            // 若nextStartPrimaryKey不为null, 则继续读取.
            if (getRangeResponse.getNextStartPrimaryKey() != null) {
                rangeRowQueryCriteria.setInclusiveStartPrimaryKey(getRangeResponse.getNextStartPrimaryKey());
            } else {
                break;
            }
        }
        return getList;
    }
    

}
